ROOM_OB = class("ROOM_OB")
ROOM_OB:inherit(F_COMN_DBASE)
ROOM_OB:inherit(F_COMN_ID)

------------------------
--匹配的房间
--[[
    begin_time : 房间创建的开始时间
    users : {
        _user_id 玩家id : user_ob 玩家对象,
    }
]]
------------------------

function ROOM_OB:get_begin_time()
    return self:query_temp("begin_time")
end

function ROOM_OB:set_begin_time(begin_time)
    return self:set_temp("begin_time", begin_time)
end

---! 获取所有users
function ROOM_OB:get_users()
    local users = self:query_temp("users")
    if not users then
        users = self:set_temp("users", {})
    end
    return users
end

---! 获取所有user ids
function ROOM_OB:get_user_ids()
    return table.keys(self:get_users())
end

---! 获取所有user obs
function ROOM_OB:get_user_obs(exclude_robot)
    local user_obs = {}
    for _, user_ob in pairs(self:get_users()) do
        if not exclude_robot or not user_ob:is_robot() then
            table.insert(user_obs, user_ob)
        end
    end
    return user_obs
end

---! 获取房间人数
function ROOM_OB:get_user_num(exclude_robot)
    local user_obs = self:get_user_obs(exclude_robot)
    return #user_obs
end

---! 获取一个用户
function ROOM_OB:get_user(user_id)
    local users = self:get_users()
    return users[user_id]
end

---! 刪除
function ROOM_OB:del_user(user_id)
    local users = self:get_users()
    local user_ob = users[user_id]
    if user_ob then
        ---! 清理玩家映射
        users[user_id] = nil

        ---! 清理玩家数据
        user_ob:clear_room()

        ---! 返回清理对象
        return user_ob
    end
end

---! 增加
function ROOM_OB:add_user(user_ob)
    local users = self:get_users()
    user_ob:set_join_time(os.time())
    user_ob:set_room(self)
    users[user_ob:get_id()] = user_ob
end

---! 销毁
function ROOM_OB:clear_room()
    local users = self:query_temp("users")
    if users then
        for _, _user_ob in pairs(users) do
            ---! 清理玩家数据
            _user_ob:clear_room()
        end
    end

    self:delete_temp("begin_time")
    self:delete_temp("users")
    self:delete_temp("robot_names")
end

---! 广播
function ROOM_OB:brocast_packet(packet_name, packet_data, exclude_user_ids)
    local users = {}
    for _user_id, _ in pairs(self:get_users()) do
        local user = USER_D:find_user(_user_id)
        if user and not user:is_robot() then
            table.insert(users, user)
        end
    end
    return USER_D:brocast_packet(users, packet_name, packet_data, exclude_user_ids)
end

function ROOM_OB:__tostring()
    return string.format("ROOM_OB [%s:%d]", self:get_id(),self:get_user_num())
end
